<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{
            userInfo.role === "Admin" ? "社区活动管理" : "活动报名"
          }}</span>
          <el-button
            v-if="userInfo.role === 'Admin'"
            type="primary"
            @click="handleAdd"
            >添加活动</el-button
          >
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="活动名称">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入活动名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="活动地点">
          <el-input
            v-model="queryParams.location"
            placeholder="请输入活动地点"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="eventList" style="width: 100%">
        <el-table-column prop="title" label="活动名称" />
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="scope">
            {{ dayjs(scope.row.startTime).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="scope">
            {{ dayjs(scope.row.endTime).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column prop="location" label="活动地点" />
        <el-table-column label="报名情况" width="150">
          <template #default="scope">
            {{ scope.row.currentParticipants }}/{{ scope.row.maxParticipants }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <template v-if="userInfo.role === 'Admin'">
              <el-button type="primary" link @click="handleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="primary"
                link
                @click="$router.push(`/event/detail/${scope.row.id}`)"
                >查看</el-button
              >
              <el-button type="danger" link @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
            <template v-else>
              <el-button
                type="primary"
                link
                @click="$router.push(`/user/event/detail/${scope.row.id}`)"
                >查看</el-button
              >
              <el-button
                type="success"
                link
                @click="handleRegister(scope.row)"
                :disabled="
                  scope.row.currentParticipants >= scope.row.maxParticipants
                "
              >
                {{ scope.row.isRegistered ? "已报名" : "报名" }}
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNumber"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-if="userInfo.role === 'Admin'"
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="活动名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动时间" prop="time">
          <el-date-picker
            v-model="form.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入活动地点" />
        </el-form-item>
        <el-form-item label="最大人数" prop="maxParticipants">
          <el-input-number
            v-model="form.maxParticipants"
            :min="1"
            :max="1000"
          />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import {
  getEventList,
  createEvent,
  updateEvent,
  deleteEvent,
  registerEvent,
} from "@/api/event";

const router = useRouter();
const loading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const total = ref(0);
const eventList = ref([]);
const formRef = ref(null);

// 用户信息
const userInfo = ref({
  username: "",
  role: "",
});

// 获取用户信息
onMounted(() => {
  const userInfoStr = localStorage.getItem("userInfo");
  if (userInfoStr) {
    userInfo.value = JSON.parse(userInfoStr);
  }
});

// 查询参数
const queryParams = reactive({
  pageNumber: 1,
  pageSize: 10,
  title: "",
  location: "",
});

// 表单数据
const form = reactive({
  id: undefined,
  title: "",
  time: [],
  location: "",
  maxParticipants: 50,
  description: "",
});

// 表单验证规则
const rules = {
  title: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
  time: [{ required: true, message: "请选择活动时间", trigger: "change" }],
  location: [{ required: true, message: "请输入活动地点", trigger: "blur" }],
  maxParticipants: [
    { required: true, message: "请输入最大参与人数", trigger: "blur" },
  ],
  description: [{ required: true, message: "请输入活动描述", trigger: "blur" }],
};

// 获取活动列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getEventList(queryParams);
    eventList.value = res.items;
    total.value = res.total;
  } catch (error) {
    console.error("获取活动列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 查询按钮操作
const handleQuery = () => {
  queryParams.pageNumber = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  queryParams.title = "";
  queryParams.location = "";
  handleQuery();
};

// 添加按钮操作
const handleAdd = () => {
  dialogTitle.value = "添加活动";
  Object.assign(form, {
    id: undefined,
    title: "",
    time: [],
    location: "",
    maxParticipants: 50,
    description: "",
  });
  dialogVisible.value = true;
};

// 编辑按钮操作
const handleEdit = (row) => {
  dialogTitle.value = "编辑活动";
  Object.assign(form, {
    id: row.id,
    title: row.title,
    time: [dayjs(row.startTime), dayjs(row.endTime)],
    location: row.location,
    maxParticipants: row.maxParticipants,
    description: row.description,
  });
  dialogVisible.value = true;
};

// 删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm("确认要删除该活动吗？", "警告", {
    type: "warning",
  }).then(async () => {
    try {
      await deleteEvent(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      console.error("删除活动失败:", error);
    }
  });
};

// 报名按钮操作
const handleRegister = async (row) => {
  try {
    await registerEvent(row.id);
    ElMessage.success("报名成功");
    getList();
  } catch (error) {
    console.error("报名失败:", error);
  }
};

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          title: form.title,
          startTime: form.time[0],
          endTime: form.time[1],
          location: form.location,
          maxParticipants: form.maxParticipants,
          description: form.description,
        };
        if (form.id) {
          await updateEvent(form.id, data);
          ElMessage.success("更新成功");
        } else {
          await createEvent(data);
          ElMessage.success("创建成功");
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("保存活动失败:", error);
      }
    }
  });
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getList();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNumber = val;
  getList();
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
